// API基础URL - 更新于2025-08-26 20:40:00
const API_BASE_URL = '/api';

// 获取存储的token
export function getToken() {
    return localStorage.getItem('admin_token');
}

// 设置token
export function setToken(token) {
    localStorage.setItem('admin_token', token);
}

// 移除token
export function removeToken() {
    localStorage.removeItem('admin_token');
}

// 获取登录用户信息
export function getUserInfo() {
    const userStr = localStorage.getItem('admin_user');
    return userStr ? JSON.parse(userStr) : null;
}

// 设置登录用户信息
export function setUserInfo(user) {
    localStorage.setItem('admin_user', JSON.stringify(user));
}

// 移除登录用户信息
export function removeUserInfo() {
    localStorage.removeItem('admin_user');
}

// 构建请求头
export function buildHeaders() {
    const token = getToken();
    const headers = {
        'Content-Type': 'application/json',
    };
    
    if (token) {
        headers['Authorization'] = `Bearer ${token}`;
    }
    
    return headers;
}

// 处理API响应
export async function handleResponse(response) {
    if (!response.ok) {
        console.error(`API请求失败: ${response.url}, 状态码: ${response.status}`);
        
        // 解析错误数据
        const errorData = await response.json().catch(() => ({}));
        
        // 特殊处理401未授权错误，但只在非登录请求中跳转
        if (response.status === 401 && !response.url.includes('/admin/login')) {
            // 清除token和用户信息
            removeToken();
            removeUserInfo();
            
            // 跳转到登录页面
            console.log('认证失效，跳转到登录页面');
            window.location.href = '/';
        }
        
        throw new Error(errorData.message || `请求失败: ${response.status} - ${response.statusText}`);
    }
    
    return response.json();
}

// 管理员登录
export async function adminLogin(phone, password) {
    try {
        const response = await fetch(`${API_BASE_URL}/admin/login`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            credentials: 'include', // 允许跨域请求携带凭证
            body: JSON.stringify({ phone, password }),
        });
        
        const data = await handleResponse(response);
        
        if (data.success) {
            // 存储token和用户信息
            setToken(data.token);
            setUserInfo(data.user);
        }
        
        return data;
    } catch (error) {
        console.error('登录失败:', error);
        throw error;
    }
}

// 获取所有文章
export async function getAllArticles() {
    try {
        const response = await fetch(`${API_BASE_URL}/admin/articles`, {
            method: 'GET',
            headers: buildHeaders(),
        });
        
        return handleResponse(response);
    } catch (error) {
        console.error('获取文章列表失败:', error);
        throw error;
    }
}

// 获取所有轮播图
export async function getAllBanners() {
    try {
        const response = await fetch(`${API_BASE_URL}/banners`, {
            method: 'GET',
            headers: buildHeaders(),
        });
        
        return handleResponse(response);
    } catch (error) {
        console.error('获取轮播图列表失败:', error);
        throw error;
    }
}

// 获取所有用户
export async function getAllUsers() {
    try {
        const response = await fetch(`${API_BASE_URL}/admin/users`, {
            method: 'GET',
            headers: buildHeaders(),
        });
        
        return handleResponse(response);
    } catch (error) {
        console.error('获取用户列表失败:', error);
        throw error;
    }
}

// 获取所有评估记录
export async function getAllAssessments() {
    try {
        const response = await fetch(`${API_BASE_URL}/admin/assessments`, {
            method: 'GET',
            headers: buildHeaders(),
        });
        
        return handleResponse(response);
    } catch (error) {
        console.error('获取评估记录失败:', error);
        throw error;
    }
}

// 创建文章
export async function createArticle(articleData) {
    try {
        const response = await fetch(`${API_BASE_URL}/articles`, {
            method: 'POST',
            headers: buildHeaders(),
            body: JSON.stringify(articleData),
        });
        
        return handleResponse(response);
    } catch (error) {
        console.error('创建文章失败:', error);
        throw error;
    }
}

// 更新文章
export async function updateArticle(articleId, articleData) {
    try {
        const response = await fetch(`${API_BASE_URL}/articles/${articleId}`, {
            method: 'PUT',
            headers: buildHeaders(),
            body: JSON.stringify(articleData),
        });
        
        return handleResponse(response);
    } catch (error) {
        console.error('更新文章失败:', error);
        throw error;
    }
}

// 删除文章
export async function deleteArticle(articleId) {
    try {
        const response = await fetch(`${API_BASE_URL}/articles/${articleId}`, {
            method: 'DELETE',
            headers: buildHeaders(),
        });
        
        return handleResponse(response);
    } catch (error) {
        console.error('删除文章失败:', error);
        throw error;
    }
}

// 上传图片
export async function uploadImage(file) {
    try {
        const formData = new FormData();
        formData.append('file', file);
        
        const response = await fetch(`${API_BASE_URL}/admin/upload/image`, {
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${getToken()}`
            },
            body: formData
        });
        
        return handleResponse(response);
    } catch (error) {
        console.error('上传图片失败:', error);
        throw error;
    }
}

// 创建轮播图
export async function createBanner(bannerData) {
    try {
        const response = await fetch(`${API_BASE_URL}/banners`, {
            method: 'POST',
            headers: buildHeaders(),
            body: JSON.stringify(bannerData),
        });
        
        return handleResponse(response);
    } catch (error) {
        console.error('创建轮播图失败:', error);
        throw error;
    }
}

// 更新轮播图
export async function updateBanner(bannerId, bannerData) {
    try {
        const response = await fetch(`${API_BASE_URL}/banners/${bannerId}`, {
            method: 'PUT',
            headers: buildHeaders(),
            body: JSON.stringify(bannerData),
        });
        
        return handleResponse(response);
    } catch (error) {
        console.error('更新轮播图失败:', error);
        throw error;
    }
}

// 删除轮播图
export async function deleteBanner(bannerId) {
    try {
        const response = await fetch(`${API_BASE_URL}/banners/${bannerId}`, {
            method: 'DELETE',
            headers: buildHeaders(),
        });
        
        return handleResponse(response);
    } catch (error) {
        console.error('删除轮播图失败:', error);
        throw error;
    }
}

// 更新评估记录状态
export async function updateAssessmentStatus(assessmentId, status) {
    try {
        const response = await fetch(`${API_BASE_URL}/admin/assessments/${assessmentId}`, {
            method: 'PUT',
            headers: buildHeaders(),
            body: JSON.stringify({ status }),
        });
        
        return handleResponse(response);
    } catch (error) {
        console.error('更新评估记录状态失败:', error);
        throw error;
    }
}

// 获取统计数据
export async function getDashboardStats() {
    try {
        // 并行请求所有数据
        const [articlesResponse, bannersResponse, usersResponse, assessmentsResponse] = await Promise.all([
            fetch(`${API_BASE_URL}/admin/articles`, { headers: buildHeaders() }),
            fetch(`${API_BASE_URL}/admin/banners`, { headers: buildHeaders() }),
            fetch(`${API_BASE_URL}/admin/users`, { headers: buildHeaders() }),
            fetch(`${API_BASE_URL}/admin/assessments`, { headers: buildHeaders() })
        ]);
        
        const [articlesData, bannersData, usersData, assessmentsData] = await Promise.all([
            handleResponse(articlesResponse),
            handleResponse(bannersResponse),
            handleResponse(usersResponse),
            handleResponse(assessmentsResponse)
        ]);
        
        return {
            articlesCount: articlesData.data ? articlesData.data.length : 0,
            bannersCount: bannersData.data ? bannersData.data.length : 0,
            usersCount: usersData.data ? usersData.data.length : 0,
            assessmentsCount: assessmentsData.data ? assessmentsData.data.length : 0
        };
    } catch (error) {
        console.error('获取仪表盘统计数据失败:', error);
        throw error;
    }
}

// 添加普通管理员
export async function addNormalAdmin(adminData) {
    try {
        const response = await fetch(`${API_BASE_URL}/admin/add-admin`, {
            method: 'POST',
            headers: buildHeaders(),
            body: JSON.stringify(adminData),
        });
        
        return handleResponse(response);
    } catch (error) {
        console.error('添加管理员失败:', error);
        throw error;
    }
}

// 检查登录状态
export function isLoggedIn() {
    const token = getToken();
    return !!token;
}

// 检查是否为超级管理员
export function isSuperAdmin() {
    const userInfo = getUserInfo();
    return userInfo && userInfo.admin_level === 2;
}

// 修改管理员密码
export async function changeAdminPassword(oldPassword, newPassword) {
    try {
        const response = await fetch(`${API_BASE_URL}/admin/change-password`, {
            method: 'PUT',
            headers: buildHeaders(),
            body: JSON.stringify({ old_password: oldPassword, new_password: newPassword }),
        });
        
        return handleResponse(response);
    } catch (error) {
        console.error('修改密码失败:', error);
        throw error;
    }
}

// 删除管理员
export async function deleteAdmin(adminId) {
    try {
        const response = await fetch(`${API_BASE_URL}/admin/delete-admin/${adminId}`, {
            method: 'DELETE',
            headers: buildHeaders(),
        });
        
        return handleResponse(response);
    } catch (error) {
        console.error('删除管理员失败:', error);
        throw error;
    }
}